using System;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.Text;

/* 
 * Server part of Plovius remember to check ipblock in iptables
 * iptables -I INPUT -i ath0 -s CLIENT_IP -j ACCEPT
 * or just do a service iptables stop
 */

namespace PloviusServer
{
    class PloviusSrv
    {
        
#region Vairables
        
        private Boolean bool_FirstRecieve = true;
        private TcpListener tcpListener;
        private Thread listenThread;
        private String str_SrvPass = "test123";
        private const int int_const_Port = 3000;
#endregion
        
        
        public static void Main()
            {
                PloviusSrv pSrv = new PloviusSrv();
                pSrv.ListenForClients();
            }

        private void WriteOutBuffer(byte[] buffer, int Length)
            {
					for (int i = 0; i < Length; i++)
					{
                                            Console.Write(buffer[i]);
					}
					Console.Write("\n");
            }
        
        private void WriteOutString(byte[] buffer)
				{
                                    ASCIIEncoding encoder = new ASCIIEncoding();
                                    Console.WriteLine(encoder.GetString(buffer, 0, buffer.Length));
				}
        
        private void SendByte(NetworkStream clientStream, byte value)
            {
                Console.WriteLine("Trying to send " + value.ToString() + " byte(s)");
                try 
                {
                    if (clientStream.CanWrite)
                    {
                        clientStream.WriteByte(value);
                        clientStream.Flush();
                        Console.WriteLine("Done..!");
                    }
                }
                catch 
                {
                    // Sorry boy
                }
            }
        
        private bool CheckForSuccess(byte buff)
            {
                if (buff == 1)
                    return true;
                if (buff == 0)
                    return false;
                return false;
            }
        
        private void HandleClientComm(object client)
            {
                TcpClient tcpClient = (TcpClient)client;
                NetworkStream clientStream = tcpClient.GetStream();
                ASCIIEncoding encoder = new ASCIIEncoding();
                byte[] message = new byte[4096];
                int bytesRead;
                while (true)
                {
                    bytesRead = 0;
                    
                    try 
                    {
                        bytesRead = clientStream.Read(message, 0, 4096);
                        this.WriteOutString(message);
                        // Successfully recieved..
                        this.SendByte(clientStream, 5);
                    }
                    
                    catch 
                    {
                        Console.WriteLine("Error happend..");
                        // Socket error ?
                        break;
                    }
                    
                    if (bytesRead  == 0 )
                    {	Console.WriteLine("Please restart, connection lost..");
                        Environment.Exit(0);
                        // Disconnected
                        break;
                    }
                }
                // If we get to here message has been successfully recieved
                Console.WriteLine(encoder.GetString(message, 0 , bytesRead));
                // Send something back!
                // Close? :x
                tcpClient.Close();
            }
	
        
        private void ListenForClients()
            {
                Console.WriteLine("Now listenening for clients..!");
                this.tcpListener.Start();
                while (true)
                {
                    // Blocks until a client has connecte..
                    TcpClient client = this.tcpListener.AcceptTcpClient();
                    Console.WriteLine("Accepted");
                    // Create a thread to handle comm with connected client
                    Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
                    clientThread.Start(client);
                }
            }
        
        public void start()
            {
                this.tcpListener = new TcpListener(IPAddress.Any, 3000);
                this.listenThread = new Thread(new ThreadStart(ListenForClients));
                this.listenThread.Start();
            }
        
        public void KillMySelf()
            {
                Environment.Exit(1);
            }	
    }
}

